package com.iyundao.io.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.iyundao.io.Service.PartymemberService;
import com.iyundao.io.model.PartyMember;
import com.iyundao.io.model.PartymemberCondition;
import com.iyundao.io.model.SysUserProvider;
import com.iyundao.io.tools.PartyMemberShow;
import com.iyundao.io.tools.PartymemberVo;
import com.iyundao.io.tools.ResponseData;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/partymember")
public class PartymemberController {

    @Autowired
    private PartymemberService partymemberService;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @ApiOperation(value="批量添加人员", notes="批量添加人员")
    @RequestMapping(value = "/batchinsert", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData batchInsert(MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseData(0,"上传文件失败，请选择文件");
        }

        //获取文件名
        String fileName = String.valueOf(System.currentTimeMillis())+".xls";

        //文件路径
        File dest = new File(uploadFolder +"file/"+ fileName);

        if(!dest.exists()){
            //先得到文件的上级目录，并创建上级目录，在创建文件
            dest.getParentFile().mkdirs();
            try {
                //创建文件
                dest.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            //文件上传
            file.transferTo(dest);

            FileInputStream fis = new FileInputStream(dest);//文件流对象
            Workbook sheets = new HSSFWorkbook(fis);

            //读取Excel表格信息
            Sheet sheet = sheets.getSheetAt(0);//读取sheet 0

            int firstRowIndex = sheet.getFirstRowNum()+1;   //第一行是列名，所以不读
            int lastRowIndex = sheet.getLastRowNum();

            List<PartymemberVo> list = new ArrayList<>();
            for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
                Row row = sheet.getRow(rIndex);
                if (row != null) {
                    /**
                     * 0:partymembername（姓名）
                     * 1:partymembersex（性别）
                     * 2:partymemberbirthday（出生年月）
                     * 3:partymemberjointime（入党时间）
                     * 4:partymemberaddress（家庭住址）
                     * 5:organizationid职务id（3.领导 4.党员）
                     * 6:partymemberphone（手机号）
                     * 7:name组织名称
                     */
                    PartymemberVo partyMember = new PartymemberVo();
                    partyMember.setPartymembername(row.getCell(0).toString());
                    partyMember.setPartymembersex(row.getCell(1).toString());
                    partyMember.setPartymemberbirthday(row.getCell(2).toString());
                    partyMember.setPartymemberjointime(row.getCell(3).toString());
                    partyMember.setPartymemberaddress(row.getCell(4).toString());

                    DataFormatter dataFormatter1 = new DataFormatter();
                    dataFormatter1.addFormat("#", null);
                    String s1 = dataFormatter1.formatCellValue(row.getCell(5));
                    partyMember.setRoleSid(s1);
                    DataFormatter dataFormatter = new DataFormatter();
                    dataFormatter.addFormat("###########", null);
                    String s2 = dataFormatter.formatCellValue(row.getCell(6));
                    partyMember.setPartymemberphone(s2);
                    partyMember.setName(row.getCell(7).toString());

                    list.add(partyMember);
                } else {
                    break;
                }
            }
            return partymemberService.batchInsert(list);

        } catch (IOException e) {
            return new ResponseData(0, e.getMessage());
        }
    }

    @ApiOperation(value="单个添加人员", notes="单个添加人员")
    @RequestMapping(value = "/insert", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData insert(@RequestBody JSONObject parmas) {
        PartyMemberShow partymemberVo = JSON.toJavaObject(parmas, PartyMemberShow.class);
       /* SysUserProvider sysUser = (SysUserProvider) SecurityUtils.getSubject().getPrincipal();
        String sid = sysUser.getSysDept().getSid();*/
        return partymemberService.insert(partymemberVo);
    }

    @ApiOperation(value="转出操作", notes="转出操作")
    @RequestMapping(value = "/rollout", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData rollOut(@RequestBody String parmas) {
        JSONObject object = JSONObject.parseObject(parmas);
        Integer id = (Integer)object.get("id");
        return partymemberService.rollOut(id);
    }

    @ApiOperation(value="转入操作", notes="转入操作")
    @RequestMapping(value = "/rolljoin", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData rollJoin(@RequestBody String parmas) {
        JSONObject object = JSONObject.parseObject(parmas);
        Integer id = (Integer)object.get("id");
        String organizationId = (String) object.get("organizationId");
        String roleId = (String) object.get("roleId");
        return partymemberService.rollJoin(id,organizationId,roleId);
    }

    @ApiOperation(value="查询未加入组织人员", notes="查询未加入组织人员")
    @RequestMapping(value = "/selectnojoin", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectNoJoin() {
        return partymemberService.selectNoJoin();
    }

    @ApiOperation(value="名称查询未加入组织人员", notes="名称查询未加入组织人员")
    @RequestMapping(value = "/selectnojoinbyname", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectNoJoin(@RequestBody String params) {
        JSONObject object = JSONObject.parseObject(params);
        String name = (String) object.get("name");
        return partymemberService.selectNoJoinByName(name);
    }

    @ApiOperation(value="根据id进行查询", notes="根据id进行查询")
    @RequestMapping(value = "/selectbyid", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectById(@RequestBody JSONObject parmas) {
        Integer id = JSON.toJavaObject(parmas, Integer.class);
        return partymemberService.selectById(id);
    }

    @ApiOperation(value="修改党员信息", notes="修改党员信息")
    @RequestMapping(value = "/updatepartymember", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData updatePartymember(@RequestBody JSONObject parmas) {
        PartyMemberShow partyMember = JSON.toJavaObject(parmas, PartyMemberShow.class);
        return partymemberService.updatePartymember(partyMember);
    }

    @ApiOperation(value="根据用户id查询组织名称以及组织下的所有人员", notes="根据用户id查询组织名称以及组织下的所有人员")
    @RequestMapping(value = "/selectpeoplebyorganizationid", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectByOrganizationId(){
        SysUserProvider sysUser = (SysUserProvider) SecurityUtils.getSubject().getPrincipal();
        return partymemberService.selectByOrganizationId(sysUser);
    }

    @ApiOperation(value="根据用户id查询组织名称以及组织下的所有人员无领导管理员", notes="根据用户id查询组织名称以及组织下的所有人员无领导管理员")
    @RequestMapping(value = "/selectpeoplebyorganizationidnomanager", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectByOrganizationIdNoManager(){
        SysUserProvider sysUser = (SysUserProvider) SecurityUtils.getSubject().getPrincipal();
        return partymemberService.selectByOrganizationIdNoManager(sysUser);
    }

    @ApiOperation(value="党员信息按条件查询", notes="党员信息按条件查询")
    @RequestMapping(value = "/selectbycondition", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectByCondition(@RequestBody JSONObject params) {
        PartymemberCondition partymemberCondition = JSON.toJavaObject(params, PartymemberCondition.class);
        return partymemberService.selectByCondition(partymemberCondition);
    }

    @ApiOperation(value="根据组织id查询特定组织下的人员，分页", notes="根据组织id查询特定组织下的人员，分页")
    @RequestMapping(value = "/selectsysid1", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectBySid1(@RequestBody String params) {
        JSONObject object = JSONObject.parseObject(params);
        String sid = (String) object.get("organizationId");
        Integer pageNum = (Integer) object.get("pageNum");
        Integer pageSize = (Integer) object.get("pageSize");
        return partymemberService.selectBySid(pageNum,pageSize,sid);
    }

    @ApiOperation(value="根据组织id查询特定组织下的人员", notes="根据组织id查询特定组织下的人员")
    @RequestMapping(value = "/selectsysid", produces = {"application/json;charset=UTF-8"})
    @CrossOrigin
    public ResponseData selectBySid(@RequestBody String params) {
        JSONObject object = JSONObject.parseObject(params);
        String sid = (String) object.get("organizationId");
        return partymemberService.selectBySid(sid);
    }

}
